import Navigator from './Navigator.js'

export default class CommonPage {
  constructor(...args) {
    if (args.length) {
      if (args[0].clazzName) {
        this.data = { clazzName: args[0].clazzName };
        Navigator.putPage(args[0].clazzName, this)
      }
    }
  }

  $init(originData) {
    //console.log(this.data)
    Object.assign(this.data = this.data ? this.data : {}, originData);
    this.$origin = JSON.parse(JSON.stringify(this.data));
    Object.freeze(this.$origin);
  }

  $take = function () {

  }
  $setData = function (data) {
    if(this.setData) {
      this.setData(data)
      console.log('PAGE SETDATA')
    } else {
      Object.assign(this.data, data)
      console.log('TEST SETDATA')
    }
  }

  //自定义路由跳转
  $route = function (path, query) {
    let page = Navigator.getPage(path)
    var path = CommonPage.$dealUrl(path, query)
    //console.log(path)
    if (page && page.$onNavigator) {
      page.$onNavigator(query)
      setTimeout(() => {
        wx.navigateTo({
          url: path,
        })
      }, 250)
    } else {
      wx.navigateTo({
        url: path,
      })
    }
  }
  //url拼接
  static $dealUrl(path, query) {
    if(query === {}) {
      return path
    } else {
      path = path + '?';
      for (var item in query) {
        path = path + `&${item}=${query[item]}`.substring()
        console.log('url：', `${path}&${item}=${query[item]}`)
      }
      //console.log(path)
      return path
    }
  }

  onUnload() {
    //console.log(this.data.clazzName)
    if (this.data.clazzName) {
      let clazz = Navigator.getPage(this.data.clazzName);
      if (!clazz || !clazz.$origin) {
        console.error('请先在页面的constructor方法中注入init(data)，以避免出现不必要的错误');
        return;
      }
      clazz.data = JSON.parse(JSON.stringify(clazz.$origin));
    }
  }

  //数据获取函数
  $put = function (key, fun, args) {
    if(key && fun) {
      CommonPage.prototype._pageValues[`${this.data.clazzName}?${key}`] = CommonPage._$delay(this, fun, args);
    }
  }

  //promise 
  static _$delay(context, cb, args) {
    return new Promise((resolve, reject) => {
      context.resolve = resolve;
      context.reject = reject;
      CommonPage.prototype.currentPageContext = context;
      cb && cb(args, resolve, reject);
    })
  }
}
//用来存放 获取到的数据 用于在页面加载完 但是数据还没获取完  在onload中防止再次请求api
CommonPage.prototype._pageValues = {};
CommonPage.prototype.currentPageContext = null;